home *** CD-ROM | disk | FTP | other *** search
/ Delphi Magazine Collection 2001 / Delphi Magazine Collection 20001 (2001).iso / DISKS / Issue67 / Threads / BasicThread.pas next >
Encoding:
Pascal/Delphi Source File  |  2001-01-05  |  2.0 KB  |  88 lines

  1. unit BasicThread;
  2.  
  3. interface
  4.  
  5. uses SysUtils,Classes,syncobjs,Windows,Messages,Forms;
  6.  
  7. type
  8.  TBasicThread=class(TThread)
  9.  protected
  10.   fException:Exception;
  11.   procedure ShowException;
  12.   function RemoveMessage(const RemoveMessage:UINT):boolean;
  13.   procedure RemoveAllMessage;
  14.   function PeekQuitMessage:boolean;
  15.  public
  16.   constructor Create(CreateSuspended: Boolean);
  17.   destructor Destroy;override;
  18.  end;
  19.  
  20. const
  21.  //WM_APP = Base for Application Message Numbers
  22.  WM_Signal_RequestWordLength=WM_APP+0;
  23.  WM_Signal_WordLengthIs=WM_APP+1;
  24.  WM_Signal_RequestLetterUsedAtPosition=WM_APP+2;
  25.  WM_Signal_Yes=WM_APP+3;
  26.  WM_Signal_No=WM_App+4;
  27.  WM_Signal_ThreadGotAnswer=WM_App+5;
  28.  WM_Signal_ThreadTerminating=WM_App+6;
  29.  
  30. var
  31.  ThreadCounter:integer;
  32.  //Note that synchronisation control is required on the 'ThreadCounter' if other
  33.  //threads other than the main thread are responsible for creating threads.
  34.  
  35. implementation
  36.  
  37. constructor TBasicThread.Create(CreateSuspended:Boolean);
  38. begin
  39.  //Were in the main VCL thread now since in this application only the main VCL
  40.  //thread creates and destroys threads.
  41.  inc(ThreadCounter);
  42.  inherited Create(CreateSuspended);
  43.  if Handle=0then
  44.   raise exception.create('Unable to Create Thread');
  45. end;
  46.  
  47. destructor TBasicThread.Destroy;
  48. begin
  49.  inherited Destroy;
  50.  Dec(ThreadCounter);
  51. end;
  52.  
  53. procedure TBasicThread.ShowException;
  54. begin
  55.  Application.ShowException(fException);
  56. end;
  57.  
  58.  
  59. function TBasicThread.RemoveMessage(const RemoveMessage:UINT):boolean;
  60. //True returned if message found and removed.
  61. var
  62.  Msg:TMsg;
  63. begin
  64.  Result:=FALSE;
  65.  while(Windows.PeekMessage(Msg,0,RemoveMessage,RemoveMessage,PM_Remove))do
  66.   Result:=TRUE;
  67. end;
  68.  
  69. procedure TBasicThread.RemoveAllMessage;
  70. var
  71.  Msg:TMsg;
  72. begin
  73.  repeat
  74.  until not(Windows.PeekMessage(Msg,0,0,0,PM_Remove));
  75. end;
  76.  
  77. function TBasicThread.PeekQuitMessage:boolean;
  78. var
  79.  Msg:TMsg;
  80. begin
  81.  Result:=Windows.PeekMessage(Msg,0,WM_Quit,WM_Quit,PM_Remove);
  82. end;
  83.  
  84. initialization
  85.  ThreadCounter:=0;
  86.  
  87. end.
  88.